﻿<?php

define('IN_ECS', true);
require('../../includes/init.php');
include_once('../../includes/lib_common.php');
include_once('../../includes/lib_transaction.php');
include_once('../../includes/lib_passport.php');

session_start();
include_once( 'config.php' );
include_once( 'weibooauth.php' );
$callback =  $callbackurl_flow;
$o = new WeiboOAuth( WB_AKEY , WB_SKEY , $_SESSION['keys']['oauth_token'] , $_SESSION['keys']['oauth_token_secret']  );

$last_key = $o->getAccessToken(  $_REQUEST['oauth_verifier'] ) ;

$_SESSION['last_key'] = $last_key;


$c = new WeiboClient( WB_AKEY , WB_SKEY , $_SESSION['last_key']['oauth_token'] , $_SESSION['last_key']['oauth_token_secret']  );
$ms  = $c->home_timeline(); // done
$me = $c->verify_credentials();



if($me['name']!==""){
  $username='weibo'.$me['id'];
  $realname=trim($me['name']);
  $password=time();//随便弄个密码 反正没有用
    $gender=$me['gender'];
  $sex = 0;
  if ($gender == 'm'){
	  $sex = 1;
  }
  elseif($gender == 'f'){
	  $sex = 2;
  }
  $email='@weibo.com';//支付宝没有返回邮箱 所以随便弄个 其他的可以根据返回情况而定
  			 /* 检测用户名 */
					function check_user($username){
					$sql = "SELECT user_id FROM " . $GLOBALS['ecs']->table("users"). " WHERE user_name='$username'";
					$row = $GLOBALS['db']->getRow($sql);
					if (!empty($row)){ return true; }else{return false;}
					}
  
  
        if (check_user($username)!==false){
					$GLOBALS['user']->set_session($username);
					$GLOBALS['user']->set_cookie($username);
					//header("Location: user.php\n");
					update_user_info();
					recalculate_price();
					echo "<script>window.opener.location='/flow.php?step=checkout';</script> ";
					echo "<script>window.close();</script> ";		
					exit;
        }else{
					$reg_date = time();
					$password =md5($password);
					$GLOBALS['db']->query('INSERT INTO ' . $GLOBALS['ecs']->table("users") . "(`email`, `user_name`, `password`, `sex`, `reg_time`, `last_login`, `last_ip`, `msn`) VALUES ('$email', '$username', '$password', '$sex', '$reg_date', '$reg_date', '$ip', '$realname')");//账号不存在 就写入数据库 并登陆
					$GLOBALS['user']->set_session($username);
					$GLOBALS['user']->set_cookie($username);
					update_user_info();
					recalculate_price();
					//header("Location: user.php\n");
					echo "<script>window.opener.location='/flow.php?step=checkout';</script> ";
					echo "<script>window.close();</script> ";		
					exit;

   		}
   
   
}else{
  echo 'fail';
  exit;
  }

?>
